using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Destructiable : MonoBehaviour
{
    public int maxHP = 100;
    private int curHP;

    public List<Sprite> injured ;
    private SpriteRenderer sprite;


    public GameObject boomPrefab;
    private void Start()
    {
        sprite =GetComponent<SpriteRenderer>();
        curHP = maxHP;
        boomPrefab = Resources.Load<GameObject>("Boom1");
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {

        TakeDamage((int)(collision.relativeVelocity.magnitude * 8));
    }
    public void TakeDamage(int damage)
    {
        curHP -= damage;
        if (curHP <= 0)
        {
            Dead();
        }
        else
        {
            Sprite before = sprite.sprite;
            int index = (int)((maxHP - curHP) / (maxHP / (injured.Count + 1.0f))) - 1;
            if (index >= 0)
                sprite.sprite = injured[index];
            if (before != sprite.sprite) PlayAudioCollsion(transform.position);
        }
    }
    protected virtual void PlayAudioCollsion(Vector3 p)
    {
        AudioManager.Instance.PlayWoodCollsion(p);
    }
    protected virtual void PlayAudioDestory(Vector3 p)
    {
        AudioManager.Instance.PlayWoodDestory(p);
    }
    public virtual void Dead()
    {
        GameObject.Instantiate(boomPrefab,transform.position,Quaternion.identity);
        Destroy(gameObject);
        PlayAudioDestory(transform.position);
    }
}
